package com.jsmtr.rms.service.impl;

import com.jsmtr.rms.dao.DaoService;
import com.jsmtr.rms.dao.impl.DaoServiceImpl;
import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.IPaperManageService;
import com.jsmtr.rms.utils.RightInterceptor;
import com.jsmtr.rms.utils.db.DbUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class PaperManageServiceIml implements IPaperManageService {
    @Resource
    DaoService dao;

    /**
     * 获取试卷列表
     * @param page
     * @param limit
     * @param position
     * @param purpose
     * @param keyWord
     * @param orderKey
     * @param orderType
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Map<String, Object> getPaperList(int page, int limit, String position, Integer purpose, String keyWord
            , String orderKey, String orderType) throws Exception {
        StringBuffer queryHQL = new StringBuffer("from PaperManage ");
        StringBuffer countHQL = new StringBuffer("select count(*) from PaperManage ");
        StringBuffer condition = new StringBuffer("where (name like '%" + keyWord + "%') ");
        if (position != "")
            condition.append("and position='" + position + "'");
        if (purpose != -1)
            condition.append("and purpose='" + purpose + "'");

        queryHQL.append(condition).append(" order by addTime desc");
        countHQL.append(condition);

        return DbUtil.pageQuery(page, limit, queryHQL.toString(), countHQL.toString(), dao);
    }

    /**
     * 获取问题列表
     * @param page
     * @param limit
     * @param keyKonwledgeID
     * @param keyLevel
     * @param keyWord
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public  Map<String, Object> getQuestionList(int page, int limit, String keyKonwledgeID, Integer keyLevel,
                                                      String typeStr, String keyWord, String position) throws Exception{
        StringBuffer queryHQL = new StringBuffer("from QuestionBank ");
        StringBuffer countHQL = new StringBuffer("select count(*) from QuestionBank ");
        StringBuffer condition = new StringBuffer("where (data like '%" + keyWord + "%') ");
        if (keyKonwledgeID != "")
            condition.append("and kid='" + keyKonwledgeID + "'");
        if (keyLevel != -1)
            condition.append("and difficulty='" + keyLevel + "'");

        condition.append("and type='" + typeStr + "'");
        condition.append("and path='" + position + "'");
        queryHQL.append(condition).append(" order by type desc");
        countHQL.append(condition);

        return DbUtil.pageQuery(page, limit, queryHQL.toString(), countHQL.toString(), dao);
    }
    /**
     * 获取知识点
     * @param page
     * @param limit
     * @param pname
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Map<String, Object> getKnowList(int page, int limit, String pname) throws Exception{
        StringBuffer queryHQL = new StringBuffer("from Knowledge ");
        StringBuffer countHQL = new StringBuffer("select count(*) from Knowledge ");
        StringBuffer condition = new StringBuffer("where (name like '%" + pname + "%') ");

        queryHQL.append(condition).append(" order by name desc");
        countHQL.append(condition);

        return DbUtil.pageQuery(page, limit, queryHQL.toString(), countHQL.toString(), dao);
    }

    /**
     * 新增试卷
     * @param paperManageTemp
     * @param paperListTemp
     * @param request
     * @return
     */
    @Override
    @Transactional
    public Integer addPaper(PaperManage paperManageTemp, List<PaperContent> paperListTemp, List<QuestionBank> questionBankList,HttpServletRequest request){
        try {
            PaperManage paperManage = (PaperManage) dao.findFirst("from PaperManage where name=:name", "name",paperManageTemp.getName());
            if (paperManage == null) {
                paperManageTemp.setId(UUID.randomUUID().toString());
                BaseUser baseUser = (BaseUser) request.getSession().getAttribute(RightInterceptor.SEESION_MEMBER);
                paperManageTemp.setAddName(baseUser.getUname());
                paperManageTemp.setAddTime(new Date());
                for(int i=0;i<paperListTemp.size();i++){
                    paperListTemp.get(i).setPid(paperManageTemp.getId());
                    paperListTemp.get(i).setId(UUID.randomUUID().toString());
                }

                List<PaperTopic> paperTopics = getTopics(paperManageTemp, questionBankList,paperListTemp);

                dao.add(paperManageTemp);
                dao.addAll(paperListTemp);
                dao.addAll(paperTopics);
                return 1;
            }else
                return 2;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 修改编辑试卷
     * @param paperManageTemp
     * @param paperListTemp
     * @return
     */
    @Override
    @Transactional
    public boolean editPaper(PaperManage paperManageTemp, List<PaperContent> paperListDel,List<PaperContent> paperListTemp,
                             List<QuestionBank> questionBankList,List<PaperTopic> paperTopicListTemp) {
        try {
            dao.update(paperManageTemp);
            dao.deleteAll(paperListDel);
            dao.addAll(paperListTemp);
            dao.deleteAll(paperTopicListTemp);
            List<PaperTopic> paperTopics = getTopics(paperManageTemp, questionBankList,paperListTemp);
            dao.addAll(paperTopics);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除试卷
     * @param paperIDs
     * @return
     */
    @Override
    @Transactional
    public boolean delPaper(String[] paperIDs) {
        try {
            List<PaperManage> paperManageList = dao.find("from PaperManage where id in(:idlist) and state = '停用'", paperIDs);
            String[] strs = new String[paperManageList.size()];
            int num = 0;
            for(PaperManage paperManage :paperManageList){
                strs[num] = paperManage.getId();
                num++;
            }
            List<PaperContent> paperContentList = dao.find("from PaperContent where pid in(:idlist)",strs);

            int cnt = 0;
            if(paperManageList.size( )> 0 ){
                dao.deleteAll(paperManageList);
                cnt++;
            }
            if(paperContentList.size() > 0){
                dao.deleteAll(paperContentList);
                cnt++;
            }

            return cnt >= 2;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 停用试卷
     * @param paperIDs
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean editClosePaper(String[] paperIDs){
        try {
            List<PaperManage> paperManageList = dao.find("from PaperManage where id in(:idlist)", paperIDs);
            if(paperManageList.size() > 0){
                for(PaperManage paperManage : paperManageList){
                    if(paperManage.getState().equals("启用"))
                        paperManage.setState("停用");
                    else
                        paperManage.setState("启用");
                }
                dao.updateAll(paperManageList);
                return true;
            }else
                return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 管理更新试卷
     * @param paperTopicList
     * @param jsonArray
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean editTopic(List<PaperTopic> paperTopicList, JSONArray jsonArray) throws Exception{
        try {
            List<PaperTopic> paperTopicListUp = new ArrayList<>();
         //   List<PaperTopic> paperTopicListDel = new ArrayList<>();

            for (Object o : jsonArray) {
                if (((JSONObject) o).get("changed").equals(true)) {
                    for (PaperTopic paperTopic : paperTopicList) {
                        if (((JSONObject) o).get("type").toString().equals(paperTopic.getType()) &&
                                ((JSONObject) o).get("number").equals(paperTopic.getNum())) {
                           // paperTopicListDel.add(paperTopic);
                            paperTopic.setKid(((JSONObject) o).get("knowID").toString());
                            String pidNew = ((JSONObject) o).get("rel").toString().split("tid=")[1].split("&pid=")[0];
                            paperTopic.setTid(pidNew);
                            paperTopicListUp.add(paperTopic);
                            break;
                        }
                    }
                }
            }

       //     dao.deleteAll(paperTopicListDel);
            dao.updateAll(paperTopicListUp);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 随机试卷更新
     * @return
     * @throws Exception
     */
    @Override
    public List<PaperTopic> editTopicRandom(PaperManage paperManageTemp, List<PaperContent> paperListTemp,
                                   List<PaperTopic> paperListDel, List<QuestionBank> questionBankListTemp) throws Exception{

        dao.deleteAll(paperListDel);
        List<PaperTopic> paperTopicListAll = getTopics(paperManageTemp, questionBankListTemp,paperListTemp);
        dao.addAll(paperTopicListAll);
        return paperTopicListAll;
    }

    private List<PaperTopic> getTopics(PaperManage pMTemp, List<QuestionBank> qBList,List<PaperContent> paperContentList) {
        List<PaperTopic> pTopics = new ArrayList<>();

        Integer[] tnum = getTopicNumber(paperContentList);
        Integer getTnum=0;
        JSONArray jsonArrayNum = new JSONArray();
        jsonArrayNum.add(tnum);
        jsonArrayNum.add(getTnum);

        JSONArray jsonArrayData = JSONArray.fromObject(qBList);

        for(int i=0;i<jsonArrayData.size();i++){
            PaperTopic paperTopicTemp = new PaperTopic();
            paperTopicTemp.setId(UUID.randomUUID().toString());
            paperTopicTemp.setKid(((JSONArray) jsonArrayData.get(i)).getString(5));
            paperTopicTemp.setTid(((JSONArray) jsonArrayData.get(i)).getString(0));
            paperTopicTemp.setPid(pMTemp.getId());
            String typeTemp = ((JSONArray) jsonArrayData.get(i)).getString(12);
            paperTopicTemp.setType(typeTemp);
            jsonArrayNum = getNo(typeTemp,jsonArrayNum);
            paperTopicTemp.setNum(Integer.parseInt(jsonArrayNum.get(1).toString()));

            pTopics.add(paperTopicTemp);
        }
        return pTopics;
    }

    private Integer[] getTopicNumber(List<PaperContent> paperContentList) {
        Integer[] tnum = {0, 0, 0, 0, 0, 0};
        Integer[] tnumTemp = {0, 0, 0, 0, 0, 0};
        Integer[] flagTemp = {0, 0, 0, 0, 0, 0};
        for (PaperContent paperCType : paperContentList) {
            if (paperCType.getTopicType().equals("单项选择题")) {
                flagTemp[0] = 1;
                tnumTemp[0] = tnumTemp[0]+paperCType.getTotalTopics();
            } else if (paperCType.getTopicType().equals("不定项选择题")) {
                flagTemp[1] = 1;
                tnumTemp[1] = tnumTemp[1]+paperCType.getTotalTopics();
            } else if (paperCType.getTopicType().equals("填空题")) {
                flagTemp[2] = 1;
                tnumTemp[2] = tnumTemp[2]+paperCType.getTotalTopics();
            } else if (paperCType.getTopicType().equals("判断正误题")) {
                flagTemp[3] = 1;
                tnumTemp[3] = tnumTemp[3]+paperCType.getTotalTopics();
            } else if (paperCType.getTopicType().equals("简答题")) {
                flagTemp[4] = 1;
                tnumTemp[4] = tnumTemp[4]+paperCType.getTotalTopics();
            } else if (paperCType.getTopicType().equals("综合题")) {
                flagTemp[5] = 1;
                tnumTemp[5] = tnumTemp[5]+paperCType.getTotalTopics();
            }
        }

        if(flagTemp[0] == 1 ){
            tnum[0] = 0;
        }
        if(flagTemp[1] == 1 ){
            tnum[1] = tnumTemp[0];
        }
        if(flagTemp[2] == 1 ){
            tnum[2] = tnumTemp[1] + tnumTemp[0];
        }
        if(flagTemp[3] == 1 ){
            tnum[3] = tnumTemp[2] + tnumTemp[1] + tnumTemp[0];
        }
        if(flagTemp[4] == 1 ){
            tnum[4] = tnumTemp[3] + tnumTemp[2] + tnumTemp[1] + tnumTemp[0];
        }
        if(flagTemp[5] == 1 ){
            tnum[5] = tnumTemp[4] + tnumTemp[3] + tnumTemp[2] + tnumTemp[1] + tnumTemp[0];
        }

        return  tnum;
    }

    private JSONArray getNo(String str, JSONArray jsonArrayNum) {
        JSONArray jsonArrayTemp = new JSONArray();

        Integer[] tnumTemp = {0,0,0,0,0,0};
        Integer getTnumTemp =0;
        for(int i=0;i<6;i++)
            tnumTemp[i] = Integer.parseInt(((JSONArray) JSONArray.fromObject(jsonArrayNum).get(0)).getString(i));

        if(str.equals("单项选择题")){
            tnumTemp[0]++;
            getTnumTemp = tnumTemp[0];
        }
        else  if(str.equals("不定项选择题")){
            tnumTemp[1]++;
            getTnumTemp = tnumTemp[1];
        }
        else  if(str.equals("填空题")){
            tnumTemp[2]++;
            getTnumTemp = tnumTemp[2];
        }
        else  if(str.equals("判断正误题")){
            tnumTemp[3]++;
            getTnumTemp = tnumTemp[3];
        }
        else  if(str.equals("简答题")){
            tnumTemp[4]++;
            getTnumTemp = tnumTemp[4];
        }
        else  if(str.equals("综合题")){
            tnumTemp[5]++;
            getTnumTemp = tnumTemp[5];
        }

        jsonArrayTemp.add(tnumTemp);
        jsonArrayTemp.add(getTnumTemp);

        return jsonArrayTemp;
    }
    /**
     * 获取试卷列表
     * @param paperID
     * @return
     * @throws Exception
     */
    @Override
    public PaperManage getPaperManage(String paperID) throws Exception{
        return (PaperManage) dao.findUnique("from PaperManage where id=:id", "id", paperID);
    }

    /**
     * 获取试卷内容列表
     * @param paperID
     * @return
     * @throws Exception
     */
    @Override
    public List<PaperContent> getPapers(String paperID) throws Exception {
        return dao.find("from PaperContent where pid = '"+paperID+"' order by chapter,sort");
    }

    /**
     * 分类获取试卷章节内容
     * @param paperID
     * @return
     * @throws Exception
     */@Override
    public List<PaperContent> getPaperTexts(String paperID,String topicType) throws Exception{
        return dao.find("from PaperContent where pid = '"+paperID+"'  and topicType = '"+topicType+"'  order by sort");
    }

    /**
     * 获取试卷章节名称
     * @param paperID
     * @return
     * @throws Exception
     */
    @Override
    public List<PaperContent> getPaperCTByChapter(String paperID) throws Exception {
        return dao.find("from PaperContent where id in(select  min(id) from PaperContent where pid = '"+paperID+"' group by chapter)");
    }
    /**
     * 获取试卷知识点
     * @param paperID
     * @return
     * @throws Exception
     */
    @Override
    public List<PaperContent> getPaperCTByKnow(String paperID) throws Exception {
        return dao.find("from PaperContent where id in(select  min(id) from PaperContent where pid = '"+paperID+"' group by kid)");
    }



    /**
     * 获取岗位列表
     * @return
     * @throws Exception
     */
    @Override
    public List<BaseJob> getJobs() throws Exception{
        return dao.find("from BaseJob where 1=1 order by name");
    }

    /**
     * 获取知识点管理列表
     * @return
     * @throws Exception
     */
    @Override
    public List<KnowManage> getKnowManageList() throws Exception{
        return dao.find("from KnowManage where 1=1 ");
    }

    /**
     * 获取知识点管理列表
     * @return
     * @throws Exception
     */
    @Override
    public List<KnowManage> getKnowManageList(String[] id) throws Exception{
        return  dao.find("from KnowManage where id in(:idlist) ",id);
    }

    /**
     * 获取知识点管理列表
     * @return
     * @throws Exception
     */
    @Override
    public List<Knowledge> getKnowledgeListGroup(String name) throws Exception{
        return dao.find("from Knowledge where id in(select  min(id) from Knowledge where  name = '"+name+"' group by kid)");
    }


    /**
     * 获取知识点管理列表
     * @return
     * @throws Exception
     */
    @Override
    public List<Knowledge> getKnowledgeList(String[] kids,String name) throws Exception{
        return dao.find("from Knowledge where kid id in(:idlist) and where  name = '"+name+"'",kids);
    }

    /**
     * 获取知识点管理列表
     * @return
     * @throws Exception
     */
    @Override
    public KnowManage getKnowManageByID(String id) throws Exception{
        return (KnowManage) dao.findUnique("from KnowManage where id = '"+id+"'");
    }
    /**
     * 获取知识点管理列表
     * @return
     * @throws Exception
     */
    @Override
    public KnowManage getKnowManageByName(String name) throws Exception{
        return (KnowManage) dao.findUnique("from KnowManage where name = '"+name+"'");
    }

    /**
     * 获取问题列表
     * @param kid
     * @param type
     * @param num
     * @return
     * @throws Exception
     */
    @Override
    public List<QuestionBank> getQuestionListRandom(String[] kid, String[] type, Integer[] num,String position) throws Exception{
        String str = "";
        for(int i=0;i<num.length;i++){
            str += "SELECT * FROM (SELECT * FROM QUESTIONBANK where KID='"+kid[i]+"' and TYPE='"+type[i]+"' " +
                    "and path = '"+position+"' ORDER BY DBMS_RANDOM.RANDOM()) WHERE ROWNUM <= "+num[i]+" union all ";
        }
        if(num.length>0)
            str = str.substring(0, str.length()-10);

        List<QuestionBank> quesList = new ArrayList<>();

        if(!str.equals(""))
            quesList = dao.findSql(str);

        return  quesList;
    }

    /**
     * 获取题目列表
     * @return
     * @throws Exception
     */
    @Override
    public List<PaperTopic> getPaperTopicList(String pid,String orderKey) throws Exception{
        return dao.find("from PaperTopic where pid='"+pid+"' order by "+orderKey);
    }
    /**
     * 获取题目列表
     * @return
     * @throws Exception
     */
    public List<PaperTopic> getPaperTopicListByType(String pid, String type) throws Exception{
        return dao.find("from PaperTopic where pid='"+pid+"'and type = '"+type+"'");
    }

    /**
     * 获取题目名称
     * @return
     * @throws Exception
     */
    @Override
    public List<QuestionBank> getTopicListByKidType(String[] kid, String type) throws Exception{
        return  dao.find("from QuestionBank where kid in(:idlist) and type = '"+type+"'",kid);
    }
    /**
     * 获取题目名称
     * @return
     * @throws Exception
     */
    @Override
    public List<QuestionBank> getTopicListByKid(String[] kid) throws Exception{
        return  dao.find("from QuestionBank where kid in(:idlist)",kid);
    }
    /**
     * 获取题目名称
     * @return
     * @throws Exception
     */
    @Override
    public List<QuestionBank> getTopicListByKidPosition(String kid, String type,String position) throws Exception{
        return  dao.find("from QuestionBank where kid = '"+kid+"' and type = '"+type+"' and path = '"+position+"'");
    }
    /**
     * 获取题目名称
     * @return
     * @throws Exception
     */
    @Override
    public List<QuestionBank>  getTopicList(String[] id) throws Exception{
        return  dao.find("from QuestionBank where id in(:idlist) ",id);
    }


    /**
     * 获取题目名称
     * @return
     * @throws Exception
     */
    @Override
    public List<QuestionBank>  getTopicList(String kid) throws Exception{
        return  dao.find("from QuestionBank where kid='"+kid+"'");
    }

    /**
     * 获取题目名称
     * @return
     * @throws Exception
     */
    @Override
    public QuestionBank  getQuestion(String id) throws Exception{
        return (QuestionBank) dao.findUnique("from QuestionBank where id='"+id+"'");
    }

    /**
     * 获取题目名称
     * @return
     * @throws Exception
     */
    @Override
    public PaperTopic getTopicByTPid(String tid,String pid) throws Exception{
        return (PaperTopic) dao.findUnique("from PaperTopic where tid='"+tid+"' and pid ='"+pid+"'");
    }

    public void setDao(DaoService dao) {
        this.dao = dao;
    }
}
